package pilgun.Multithread.CircularBuffer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class CircularBufferImpl2 implements CircularBuffer{
	final private int len;
	final String[] arr;
	private int start = 0;
	private int occupied = 0;
	private Lock lock = new ReentrantLock();
	private Condition cond = lock.newCondition();
	
	public CircularBufferImpl2(int len) {
		this.len = len;
		arr = new String[len];
	}
	
	public void put (String elem) throws InterruptedException{
		lock.lock();
		try{
			while (len == occupied){
				cond.await();
			}
			int end = (start + occupied) % (len);
			occupied++;
			arr[end] = elem;
			cond.signalAll();
		}
		finally{
			lock.unlock();
		}
	}
	
	public String get () throws InterruptedException{
		lock.lock();
		try{
			while (occupied == 0){
				cond.await();
			}
			occupied--;
			String elem = arr[start];
			start = (start+1)%len;
			cond.signalAll();
			return elem;
		}
		finally{
			lock.unlock();
		}
	}
}